/**
 * @author Tibor Kiray
 */
function EntityCreateField(fieldType, entityId){

	fieldTypesArr = [
				        ['TextField', 'Text Field'],
				        ['TextArea', 'Text Area'],
				        ['HtmlEditor', 'Html Editor'],
				        ['TimeField', 'Time Field'],
				        ['DateField', 'Date Field'],
						['DiskFile', 'File on Disk'],
						['DBFile', 'File in DB'],
						['SSLookupField', 'Single Lookup Field'], //single selection
						['MSLookupField', 'Multiple Lookup Field'] //multiple selection
			        ];

	var fieldTypesStore = new Ext.data.SimpleStore({
	    fields: ['fieldTypeVal', 'fieldTypeName'],
	    data : fieldTypesArr});
	
	var combo = new Ext.form.ComboBox({
		store: fieldTypesStore,
		name: 'field_type',
        fieldLabel: 'Field Type',
        displayField: 'fieldTypeName',
        valueField: 'fieldTypeVal',
        typeAhead: true,
        forceSelection: true,
        mode: 'local',
        triggerAction: 'all',
        selectOnFocus: true,
        editable: true,
        xtype: 'combo',
        width: 127,
        emptyText: 'Select a type...',
        listeners: {
            change: function(combo, newValue, oldValue){
                //alert("change");
                //console.log("Old Value: " + oldValue);
                //console.log("New Value: " + newValue);
            },
            
            // 'select' will be fired as soon as an item in the ComboBox is selected with mouse, keyboard.
            select: function(combo, record, index){
                //alert(domainForm.getComponent("selection"));
                //domainForm.getComponent("selectedDomain").setRawValue(record.data.ID);
				EntityFieldCreateForm.getComponent("selectedType").setRawValue(record.data.fieldTypeVal)
				//alert(record.data.fieldTypeVal);
                //console.log(record.data.name);
                //console.log(index);
                //console.log(record.data.ID);
            }
        }	            
	});
	combo.setValue(fieldType);
	var EntityFieldCreateForm = new Ext.FormPanel({
		id				: 'EntityFieldCreateForm',
		standardSubmit	: false,
		title 			: '',
		//action		: 'server/EntitySave.php',
		//url				: 'server/EntityFieldCreate.php',
		width			: 'auto',
		height			: 'auto',
		autoScroll		: true,
		labelWidth		: 150,
		//height			: 500,
		//width			: 700,
		isUpload		: true,
		defaultType		: "textfield",
		monitorValid	: true,
		buttonAlign		: "center",
		items			: [
							combo,
							{
								name: 'entityId',
								xtype: 'hidden',
								value: entityId
							},{
								name: 'selectedType',
								id: 'selectedType',
								xtype: 'hidden',
								value: fieldType
							},{
								fieldLabel: 'Name',
								name: 'name',
								//vtype: 'alphanum',
								allowBlank: false
							},{
								fieldLabel: 'Database field',
								name: 'db_field',
								vtype: 'alphanum',
								allowBlank: false
							},{
								fieldLabel: 'Grid header',
								name: 'grid_header',
								//vtype: 'alphanum',
								allowBlank: false
							},{
								fieldLabel: 'Form location', //if empty will be rendered last on the form
								name: 'form_location',
								vtype: 'numeric',
								allowBlank: false
							},{
								fieldLabel: 'Grid location', //if empty not visible on grid
								name: 'grid_location',
								vtype: 'numeric',
								allowBlank: true
							},{
					                xtype: 'radiogroup',
					                fieldLabel: 'Single Column',
					                itemCls: 'x-check-group-alt',
					                columns: 1,
					                items: [
					                    {boxLabel: 'Item 1', name: 'rb-col', inputValue: 1},
					                    {boxLabel: 'Item 2', name: 'rb-col', inputValue: 2, checked: true},
					                    {boxLabel: 'Item 3', name: 'rb-col', inputValue: 3}
					                ]
					            },{
								xtype:'fieldset',
					            title: 'Radio Groups',
					            autoHeight: true,
								//itemCls: "app-radio-group",
								//clearCls: "app-radio-group",
					            items: [{
					                xtype: 'textfield',
					                name: 'txt-test4',
					                fieldLabel: 'Alignment Test',
					                anchor: '95%'
					            },{
					                xtype: 'radiogroup',
					                fieldLabel: 'Auto Layout',
					                items: [
					                    {boxLabel: 'Item 1', name: 'rb-auto', inputValue: 1},
					                    {boxLabel: 'Item 2', name: 'rb-auto', inputValue: 2, checked: true},
					                    {boxLabel: 'Item 3', name: 'rb-auto', inputValue: 3},
					                    {boxLabel: 'Item 4', name: 'rb-auto', inputValue: 4},
					                    {boxLabel: 'Item 5', name: 'rb-auto', inputValue: 5}
					                ]
					            },{
					                xtype: 'radiogroup',
					                fieldLabel: 'Single Column',
					                itemCls: 'x-check-group-alt',
					                columns: 1,
					                items: [
					                    {boxLabel: 'Item 1', name: 'rb-col', inputValue: 1},
					                    {boxLabel: 'Item 2', name: 'rb-col', inputValue: 2, checked: true},
					                    {boxLabel: 'Item 3', name: 'rb-col', inputValue: 3}
					                ]
					            }]
							}],
							buttons:[{
										text:'Salveaza',
										formBind:true,
										scope:this,
										handler:function() {
											EntityFieldCreateForm.getForm().doAction('submit', {url:'server/EntityFieldCreate.php'})
									    }
									}]
	});
	//EntityFieldCreateForm.add
	EntityFieldCreateForm.on({
        	actioncomplete: function(form, action){
                            // Only enable the submit button if the load worked
            if(action.type == 'load'){
                submit.enable();
                Ext.MessageBox.alert('fs.actioncomplete', 'All OK.'); // Optional. Just for testing
            } 
            if(action.type == 'submit'){
                        // If the responseText is a null string, Ext doesnt raise an error so trap it here 
                        // as an error because it should be some json.
                if (action.response.responseText == '') {
					Ext.MessageBox.alert('fs.actioncomplete error', 'Form submit returned an empty string instead of json');
				}
				else {
					var result = Ext.decode(action.response.responseText);
					Ext.MessageBox.alert('Result', result.msg);
					win.close();
					//entity_tree.root.reload();
				}
            }
        },
                        // The following code could be rationalised but I did it this way to make it easier
                        // to follow and for you to test it yourself.
                        // NOTE: the line var result = Ext.decode(action.response.responseText); must be
                        // called AFTER you have made sure there wasnt a failureType == "connect" or you 
                        // will probably get a JS error in the Ext library.
                            
        actionfailed: function(form,action){
            //alert('actionfailed');            
            if(action.type == 'load') { // Handle the LOAD errors
                if (action.failureType == "connect") { 
                    Ext.MessageBox.alert('fs.actionfailed error', 'Form load failed. Could not connect to server.');
                } else {
                    if (action.response.responseText != '') {
                        var result = Ext.decode(action.response.responseText);
                        if(result && result.msg) {            
                            Ext.MessageBox.alert('fs.actionfailed error', 'Form load failed with error: ' + action.result.msg);
                        } else {
                            Ext.MessageBox.alert('fs.actionfailed error', 'Form load failed with unknown error (possibly missing the "success" field in the json). Action type='+action.type+', failure type='+action.failureType);
                          }
                    } else {
                        Ext.MessageBox.alert('fs.actionfailed error', 'Form load returned an empty string instead of json');
                      }
                  }
            } 

            if(action.type == 'submit') { // Handle the SUBMIT errors
				
                if (action.failureType == "connect") { 
                    Ext.MessageBox.alert('fs.actionfailed error', 'Form submit failed. Could not connect to server.');
                } else 
                    if (action.failureType == "server") { 
                        // These arent "errors" as such, they are validation issues trapped by the server script and passed back for the user to correct
                    } else {    
                        var result = Ext.decode(action.response.responseText); 
                        if(result && result.msg) {            
                            Ext.MessageBox.alert('fs.actionfailed error', 'Form submit failed with error: ' + action.result.msg);
                        } else {
                            Ext.MessageBox.alert('actionfailed Error', 'Form submit returned unknown error. Action type='+action.type+', failure type='+action.failureType);
                          }
                      }
            }   
            
        } // end actionfailed listener
    }); // end fs.on
    var win = new Ext.Window({
		  width: 'auto',
		  id: 'CreateEntityWindow',
		  autoScroll: true,
		  modal: true,
		  height: 'auto',
		  width: 300,
		  onEsc: function(){
		      this.close()
		  },
		  title: 'Entity create field',
		  iconCls: 'btn-add',
		  listeners: {
		      show: function(){
		          this.loadMask = new Ext.LoadMask(this.body, {
		              msg: 'Loading. Please wait...'
		          });
		      }
		  }
	});
	win.add(EntityFieldCreateForm);
	win.show();
	//return entityForm;
}
